package com.stadium.web.service.impl;

import com.fastsite.cache.ehcache.utils.EhCacheUtil;
import com.fastsite.common.api.ApiException;
import com.fastsite.utils.EncryptUtil;
import com.stadium.web.service.FileService;
import org.apache.commons.codec.digest.Md5Crypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Service
public class FileServiceImpl implements FileService {
    // 制作文件的白名单,使用Arrays.asList列出一个常量的字符串
    @Value("${project.file-upload-path}")
//    private static final List<String> CONTENT_TYPES = Arrays.asList("image/gif","image/jpeg","image/png","doc","pdf","txt");
    // 定义输出错误日志
    private static final Logger LOGGER = LoggerFactory.getLogger(FileServiceImpl.class);

    /**
     * 根据工作内容ID查询工作内容数据
     * @param id 工作内容ID
     */
    @Value("${project.file-upload-path}")
    private String FILE_UPLOAD_PATH;

    public String uploadFile(HttpServletRequest request, MultipartFile file, String fileName) {
        if(fileName==null){
            fileName="file"+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        }
        //避免重复去重
        String hash = EncryptUtil.encrypt(LocalDateTime.now().toString(),"date").substring(0,7);
        //图片访问的URI
        String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/static/imgs";

        // 获取文件类型
        String originalFilename = "/"+hash+"_"+fileName;
            // 校验文件类型
            // 列出所有文件合法类型
            String contentType = file.getContentType();
//            if (!CONTENT_TYPES.contains(contentType)){
//                LOGGER.info("文件类型不合法：{}",originalFilename);
//                throw new ResultException("文件类型不合法："+originalFilename);
//            }

            // 校验文件的内容，ImageIO读取文件内容
//            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
//            if (bufferedImage == null) {
//                LOGGER.info("文件内容不合法：{}",originalFilename);
//                return null;
//            }
            String path ="/opt/nginx/resources/";
            if(System.getProperty("os.name").startsWith("Windows")){
                path = "D:\\\\tmp\\file\\";
            }
            LocalDate date =  LocalDate.now();
            String  sDate = date.toString().replace("-","/");
            String savePath = path+sDate+originalFilename;

            File fileIn = new File(savePath);
            File filePath =  new File(path+sDate);
            if(!filePath.isDirectory()){
                filePath.mkdirs();
            }

            // 保存到服务器
        try {
                //将上传的文件写到服务器上指定的文件。
                file.transferTo(fileIn);
                String projectPath = System.getProperty("user.dir");
                String url= returnUrl + "/" + sDate+originalFilename;
                return url;
            } catch (IOException e) {
                LOGGER.info("服务器内部错误：" + originalFilename);
                e.printStackTrace();
                throw new ApiException("文件上传失败");
            }

    }

    /**
     * 文件复制
     * @param src
     * @param destDir
     * @param fileName
     * @throws IOException
     */
    public void copyFile(String src,String destDir,String fileName) throws IOException{
        FileInputStream in=new FileInputStream(src);
        File fileDir = new File(destDir);
        if(!fileDir.isDirectory()){
            fileDir.mkdirs();
        }
        File file = new File(fileDir,fileName);

        if(!file.exists()){
            file.createNewFile();
        }
        FileOutputStream out=new FileOutputStream(file);
        int c;
        byte buffer[]=new byte[1024];
        while((c=in.read(buffer))!=-1){
            for(int i=0;i<c;i++){
                out.write(buffer[i]);
            }

        }
        in.close();
        out.close();
    }
}
